<template>
  <div class="approval-form-page pl-3">
    <div class="approval-form">
      <div class="approval-form-container">
        <div class="form-content-title">基本信息</div>
        <BasicForm :disabled="disabled" @register="registerForm" ref="formRef" />
        <!-- 子表单区域 -->
        <div class="form-content-title sub-form-content-title">元素列表</div>
        <a-tabs v-model:activeKey="activeKey" animated @change="handleChangeTabs">
          <a-tab-pane tab="立项金额附表" key="projectAmountDetail" :forceRender="true">
            <JVxeTable
              keep-source
              resizable
              ref="projectAmountDetail"
              v-show="projectAmountDetailTable.show"
              :loading="projectAmountDetailTable.loading"
              :columns="projectAmountDetailTable.columns"
              :dataSource="projectAmountDetailTable.dataSource"
              :height="340"
              :rowNumber="true"
              :rowSelection="true"
              :toolbar="true"
              :disabled="disabled"
            />
          </a-tab-pane>
        </a-tabs>

        <div v-if="curProcessInstanceId">
          <VBlaDiscuss
            ref="discussRef"
            :theme="appTheme"
            :locale="locale"
            :processInstanceId="curProcessInstanceId"
            :innerStyle="{ borderRadius: '8px' }"
          />
        </div>
      </div>
    </div>

    <div class="approval-components" :class="[operate ? 'page-operate-' + operate : '', isInModal ? 'is-in-modal' : '']">
      <template v-if="curProcessInstanceId">
        <VBlaDecision
          ref="decisionRef"
          :theme="appTheme"
          :taskId="taskId"
          :locale="locale"
          :hideUrge="false"
          :beforeBtnClick="onApprovalBeforeBtnClick"
          :decisionClick="decisionClick"
        />
        <VBlaRecordPreview
          ref="recordPreviewRef"
          :theme="appTheme"
          :locale="locale"
          :processInstanceId="curProcessInstanceId"
          :previewHeight="500"
          :widgetsShowConfig="displayConfig"
          @view-chart="handleViewChart"
        />
      </template>
      <div v-else class="create-approval">
        <div class="create-approval-title">处理</div>
        <a-textarea v-model:value="submitMessage" placeholder="请输入处理意见(选填)" :rows="6"></a-textarea>
        <a-space class="create-approval-btns">
          <a-button :disabled="disabled" @click="onSubmitNormal" type="primary">提交</a-button>
          <a-button :disabled="disabled" v-auth="'projectproposalpreparation:project_proposal_preparation:saveDraft'" @click="onDraft">保存草稿</a-button>
          <a-button v-if="flowchartOptions.length === 1" @click="openFlowchart()">流程图</a-button>
          <a-dropdown v-if="flowchartOptions.length > 1">
            <template #overlay>
              <a-menu @click="openFlowchart">
                <a-menu-item v-for="(item, index) in flowchartOptions" :key="index">
                  {{ item.processName }}
                </a-menu-item>
              </a-menu>
            </template>
            <a-button>
              流程图
              <DownOutlined />
            </a-button>
          </a-dropdown>
        </a-space>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
  import { BasicForm, useForm, useFormPermit } from '/@/components/Form/index';
  import { computed, defineComponent, inject, onMounted, reactive, ref, watch } from 'vue';
  import { propTypes } from '/@/utils/propTypes';
  import { useJvxeMethod } from '/@/hooks/system/useJvxeMethods';
  import { getBpmFormSchema, projectAmountDetailColumns, approvalRunTaskBo } from './ProjectProposalPreparation.data';
  import {
    projectAmountDetailList,
    submit,
    saveProcess,
    saveDraft,
    getDataByTaskId,
    queryDataById,
    approvalFindNextNodeUserUrl,
    queryFlowchart,
  } from './ProjectProposalPreparation.api';
  import { useRoute } from 'vue-router';
  import { getToken } from '/@/utils/auth';
  import { VBlaDiscuss, VBlaDecision, VBlaRecordPreview } from '@byteluck/approval-wc-widgets-desktop';
  import { useTabs } from '/@/hooks/web/useTabs';
  import { useApprovalMethods } from '/@/hooks/system/useApprovalMethods';

  export default defineComponent({
    name: 'ProjectProposalPreparationApproval',
    components: {
      BasicForm,
      VBlaDiscuss,
      VBlaDecision,
      VBlaRecordPreview,
    },
    props: {
      formData: propTypes.object.def({}),
      formBpm: propTypes.bool.def(true),
      formDisabled: propTypes.bool.def(false),
      taskId: propTypes.string.def(''),
      isInModal: propTypes.bool.def(false),
      recordId: propTypes.string.def(''),
      processInstanceId: propTypes.string.def(''),
      processStatus: propTypes.string.def(''),
      operate: propTypes.string.def(''),
      isApprovalNew: propTypes.number.def(0),
    },
    emits: ['success'],
    setup(props, { emit }) {
      const token = getToken();
      const { close: closeTab } = useTabs();
      const appTheme = inject('appTheme');
      window.approvalConfig.headers = {
        authorization: token,
        'x-access-token': token,
      };
      const route = useRoute();
      const displayConfig = ref({
        flow_virtual: 'DISPLAY',
        approval_record: 'DISPLAY',
      });
      const curProcessInstanceId = ref('');
      const taskId = ref(route.query.taskId);

      const locale = ref('zh');
      const submitMessage = ref('');
      const flowchartOptions = ref<any[]>([]);

      let permitEnum = ref([]);
      let { judgeIf, judeRequired, judgeRead } = useFormPermit(permitEnum);
      const [registerForm, { setFieldsValue, setProps, clearValidate }] = useForm({
        labelWidth: 150,
        schemas: getBpmFormSchema(props.formData, { judgeIf, judeRequired, judgeRead }),
        showActionButtonGroup: false,
        baseColProps: { span: 12 },
      });

      onMounted(() => {
        clearValidate();
      });

      const disabled = computed(() => {
        if (props.formBpm === true) {
          if (props.formData?.disabled === true) {
            return true;
          } else {
            return false;
          }
        }
        return props.formDisabled;
      });

      const refKeys = ref(['projectAmountDetail']);
      const activeKey = ref('projectAmountDetail');

      const projectAmountDetail = ref();

      const childprojectAmountDetailColumns = computed(() => {
        return projectAmountDetailColumns.reduce((pre: any[], cur) => {
          if (!judgeIf(cur.filedkey, true)) {
            return pre;
          }
          let mItem = { ...cur };
          mItem.disabled = judgeRead(cur.filedkey, cur.disabled);

          let required = judeRequired(cur.filedkey, cur.validateRules?.length);
          if (!required) {
            mItem.validateRules = [];
          } else {
            mItem.validateRules = ([] as any[]).concat(cur.validateRules);
          }
          pre.push(mItem);
          return pre;
        }, []);
      });

      const projectAmountDetailTable = reactive({
        loading: false,
        dataSource: [],
        columns: childprojectAmountDetailColumns,
        show: false,
      });

      const tableRefs = { projectAmountDetail };

      const { handleChangeTabs, handleSubmit, requestSubTableData, formRef, getFullData, getFullDataNoValidate } = useJvxeMethod({
        requestAddOrEdit,
        classifyIntoFormData,
        tableRefs,
        activeKey,
        refKeys,
        props,
      });

      const { onApprovalBeforeBtnClick } = useApprovalMethods({
        getFormData: getFullData,
        approvalFindNextNodeUserUrl,
        taskId: taskId,
      });

      async function requestAddOrEdit(values) {
        // await saveOrUpdate(values, true);
        return values;
      }

      function classifyIntoFormData(allValues) {
        let main = Object.assign({}, allValues.formValue);
        return {
          ...main,
          projectAmountDetailList: allValues.tablesValue[0].tableData,
        };
      }

      const closePage = () => {
        if (props.isInModal) {
          emit('success');
        } else {
          if (props.taskId !== undefined) {
            window.parent.setvvisible();
          } else {
            closeTab();
          }
        }
      };

      const openFlowchart = (info?: any) => {
        let index = 0;
        if (info) {
          index = info.key;
        }
        let item = flowchartOptions.value[index];
        const previewchartPath = window.approvalConfig?.previewchartPath || '';
        const processKey = item.processKey;
        const processName = item.processName;
        const view_url = `${previewchartPath}/ego-bpa-front/#/home/FlowDetail?processKey=${processKey}&processName=${processName}`;
        window.open(view_url, '_blank');
      };

      async function onSubmitNormal() {
        let data = await getFullData();
        if (props.recordId) {
          await saveProcess({
            data,
            runTaskBo: {
              ...approvalRunTaskBo,
              task_comment: submitMessage.value,
            },
          });
        } else {
          await submit({
            data,
            runTaskBo: {
              ...approvalRunTaskBo,
              task_comment: submitMessage.value,
            },
          });
        }

        closePage();
      }

      const onDraft = async () => {
        const values = await getFullDataNoValidate();
        await saveDraft(values);

        closePage();
      };

      async function initFlowchartOptions() {
        const list = await queryFlowchart();
        flowchartOptions.value = list;
      }

      async function initFormData() {
        let params;
        if (props.taskId) {
          taskId.value = props.taskId;
        }
        if (taskId.value) {
          params = { taskInstanceId: taskId.value };
        } else if (props.processInstanceId) {
          params = { processInstanceId: props.processInstanceId };
        }
        if (!taskId.value && !props.recordId && !props.processInstanceId && props.operate !== 'create') {
          return;
        }

        if (props.operate === 'create' || props.processStatus === 'DRAFT') {
          initFlowchartOptions();
        }

        let res: any;
        let mainRecordId = '';
        let mainFormData: any;
        if (taskId.value || props.processInstanceId) {
          res = await getDataByTaskId(params);
          curProcessInstanceId.value = res.processParam?.processInstanceId;
          permitEnum.value = res.permissions;
          mainRecordId = res?.data?.id;
          mainFormData = res.data;
        } else if (props.recordId) {
          res = await queryDataById(props.recordId);
          mainRecordId = props.recordId;
          mainFormData = res;
        }
        if (res) {
          await setFieldsValue({ ...mainFormData });
        }

        requestSubTableData(projectAmountDetailList, { id: mainRecordId }, projectAmountDetailTable, () => {
          projectAmountDetailTable.show = true;
        });

        await setProps({ disabled: disabled.value });
      }

      const decisionClick = async (evt) => {
        if (evt.command_id === 'generalTaskNotice') {
          return;
        }
        // 执行内部提交
        let res = await handleSubmit();
        await saveProcess({
          data: res,
          runTaskBo: evt,
        });

        closePage();
      };

      const handleViewChart = () => {
        const previewchartPath = window.approvalConfig?.previewchartPath || '';
        const view_url = `${previewchartPath}/ego-bpa-front/#/home/FlowDetail?uId=${curProcessInstanceId.value}`;
        window.open(view_url, '_blank');
      };

      watch(
        () => props.isApprovalNew,
        (val) => {
          initFormData();
        },
        { immediate: true }
      );

      return {
        registerForm,
        disabled,
        formRef,
        handleSubmit,
        activeKey,
        handleChangeTabs,
        decisionClick,
        onApprovalBeforeBtnClick,
        displayConfig,
        taskId,
        locale,
        curProcessInstanceId,
        handleViewChart,
        appTheme,
        projectAmountDetail,
        projectAmountDetailTable,
        submitMessage,
        onSubmitNormal,
        onDraft,
        openFlowchart,
        flowchartOptions,
      };
    },
  });
</script>
<style lang="less" scoped>
  @import '/@/design/reference/form.less';

  @approval-components-width: 400px;
  .approval-form-page {
    display: flex;
    height: 100%;
    justify-content: space-between;
  }
  .approval-form {
    width: calc(100% - @approval-components-width);
    height: 100%;
    overflow: auto;
    background-color: #eee;
  }
  .approval-form-container {
    padding: 16px;
    background-color: #fff;
  }
  .approval-components {
    width: @approval-components-width;
    background-color: #fff;
    flex-shrink: 0;
    height: 100%;
    padding: 16px;

    &.is-in-modal {
      padding: 0;
    }

    & > div:last-child {
      height: calc(100% - 240px);

      :deep(.approve-progress) {
        height: 100%;
      }
      :deep(.bla-record-preview) {
        height: calc(100% - 62px);
      }
    }
  }

  .create-approval {
    padding: 12px;
  }
  .create-approval-title {
    font-size: 20px;
    font-weight: 600;
    line-height: 22px;
    color: #1f2329;
    margin-bottom: 8px;
  }

  .create-approval-btns {
    margin-top: 30px;
  }
</style>
<style lang="less">
  .process-common-modal {
    &.cyj-full-screen-modal-code-generate.process-common-modal .approval-form {
      padding: 0;
      background-color: #eee;
    }

    .approval-components {
      padding: 0;
    }
  }
</style>
